package cn.wolfcode.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
   @RequestMapping("/login")
@ResponseBody
    public JsonResult login(String username, String password){
       try{
           UsernamePasswordToken token = new UsernamePasswordToken(username, password);
           Subject subject = SecurityUtils.getSubject();
           subject.login(token);
           subject.getSession().setAttribute("EMPLOYEE_IN_SESSION",subject.getPrincipal());
           return new JsonResult(true,"登陆成功");
       } catch(UnknownAccountException e){
           return new JsonResult(false,"账号不存在");
       }catch (IncorrectCredentialsException e){
           return new JsonResult(false,"账号密码有误");
       }catch (Exception e){
           e.printStackTrace();
           return new JsonResult(false,"登录异常,请联系管理员");
       }
   }
   @RequestMapping("/logout")
    public String logout(HttpSession session){
       session.removeAttribute("EMPLOYEE_IN_SESSION");
       return "redirect:/static/login.html";
   }
}
